package com.netease.financial.base.customerservice;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Toast;

import com.netease.financial.base.web.WebStoragePreferencesHelper;
import com.netease.financial.common.config.NfsConfig;
import com.netease.financial.common.util.NfsLog;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;
import com.nostra13.universalimageloader.utils.MemoryCacheUtils;
import com.qiyukf.unicorn.api.ConsultSource;
import com.qiyukf.unicorn.api.ImageLoaderListener;
import com.qiyukf.unicorn.api.SavePowerConfig;
import com.qiyukf.unicorn.api.StatusBarNotificationConfig;
import com.qiyukf.unicorn.api.UICustomization;
import com.qiyukf.unicorn.api.Unicorn;
import com.qiyukf.unicorn.api.UnicornImageLoader;
import com.qiyukf.unicorn.api.UnreadCountChangeListener;
import com.qiyukf.unicorn.api.YSFOptions;
import com.qiyukf.unicorn.api.YSFUserInfo;

/**
 * Created by hzwuyufeng on 12/18/15.
 */
public class CustomerServiceHelper {

    private static final String TAG = CustomerServiceHelper.class.getSimpleName();

    public static boolean sCustomerServiceEnable = true;

    private static YSFOptions mYSFOptions;

    public static void setUserId(String userId) {
        if (!sCustomerServiceEnable) {
            return;
        }
        if (isUserChanged(userId)) {
            CustomerServiceHelper.logoutForCustomerService();
            CustomerServiceHelper.loginForCustomerService(userId);
        }
    }

    public static void logoutForCustomerService() {
        if (!sCustomerServiceEnable) {
            return;
        }
        NfsLog.d(TAG, "logout");
        CustomerServicePreferencesHelper.saveUserId(null);
        Unicorn.setUserInfo(null);
    }

    public static void loginForCustomerService(String userId) {
        if (!sCustomerServiceEnable) {
            return;
        }
        CustomerServicePreferencesHelper.saveUserId(userId);
        NfsLog.d(TAG, "login.userId.in:" + userId);

        YSFUserInfo userInfo = new YSFUserInfo();
        userInfo.userId = CustomerServicePreferencesHelper.getUserId();
        NfsLog.d(TAG, "login.userId2.apply:" + CustomerServicePreferencesHelper.getUserId());

        CustomerServiceHelper.setUserInfo(userInfo);
    }

    public static void saveCurrentWebPageInfo(String url, String title) {
        if (!sCustomerServiceEnable) {
            return;
        }
        CustomerServicePreferencesHelper.saveWebUrl(url);
        CustomerServicePreferencesHelper.saveWebTitle(title);
    }

    public static void removeCurrentWebPageInfo() {
        if (!sCustomerServiceEnable) {
            return;
        }
        CustomerServicePreferencesHelper.removeWebUrl();
        CustomerServicePreferencesHelper.removeWebTitle();
    }

    public static void openChatScreen(Context context) {
        if (!sCustomerServiceEnable) {
            return;
        }
        if (!CustomerServiceHelper.isServiceAvailable()) {
            // 当前客服服务不可用，一般来说就是登录云信失败
            Toast.makeText(context, "没有云信账号", Toast.LENGTH_SHORT).show();
            return;
        }
        String sourceUrl = CustomerServicePreferencesHelper.getWebUrl();
        String sourceTitle = CustomerServicePreferencesHelper.getWebTitle();
        String chatScreenTitle = CustomerServicePreferencesHelper.getChatScreenTitle();
        ConsultSource source = new ConsultSource(sourceUrl, sourceTitle, null);
        CustomerServiceHelper.openServiceActivity(context, chatScreenTitle, source);
    }

    public static void init(final Context context) {
        if (!sCustomerServiceEnable) {
            return;
        }
        Unicorn.init(context, NfsConfig.getCloudCustomerServiceAppId(), mYSFOptions = ysfOptions(), new UnicornImageLoader() {
            @Nullable
            @Override
            public Bitmap loadImageSync(String uri, int width, int height) {
                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .cacheInMemory(true)
                        .cacheOnDisk(false)
                        .bitmapConfig(Bitmap.Config.RGB_565)
                        .build();

                // check cache
                boolean cached = MemoryCacheUtils.findCachedBitmapsForImageUri(uri, ImageLoader.getInstance().getMemoryCache()).size() > 0
                        || DiskCacheUtils.findInCache(uri, ImageLoader.getInstance().getDiskCache()) != null;
                if (cached) {
                    Bitmap bitmap = ImageLoader.getInstance().loadImageSync(uri, new ImageSize(width, height), options);
                    if (bitmap == null) {
                        NfsLog.e(TAG, "load cached image failed, uri =" + uri);
                    }
                    return bitmap;
                }

                return null;
            }

            @Override
            public void loadImage(String uri, int width, int height, final ImageLoaderListener listener) {
                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .cacheInMemory(true)
                        .cacheOnDisk(false)
                        .bitmapConfig(Bitmap.Config.RGB_565)
                        .build();

                ImageLoader.getInstance().loadImage(uri, new ImageSize(width, height), options, new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        super.onLoadingComplete(imageUri, view, loadedImage);
                        if (listener != null) {
                            listener.onLoadComplete(loadedImage);
                        }
                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                        super.onLoadingFailed(imageUri, view, failReason);
                        if (listener != null) {
                            listener.onLoadFailed(failReason.getCause());
                        }
                    }
                });
            }
        }); // 初始化云商服
    }

    public static boolean isServiceAvailable() {
        if (!sCustomerServiceEnable) {
            return false;
        }
        return Unicorn.isServiceAvailable();
    }

    // context    上下文
    // title    聊天窗口的标题
    // source    咨询的发起来源，包括发起咨询的url，title，描述信息等
    private static void openServiceActivity(Context context, String title, ConsultSource source) {
        if (!sCustomerServiceEnable) {
            return;
        }
        //获取用户头像并设置
        String uri = WebStoragePreferencesHelper.getLocalStorageItem(WebStoragePreferencesHelper.KEY_LOCAL_STORAGE_HEAD_PORTRAIT_URL);
        mYSFOptions.uiCustomization.rightAvatar = uri;
        Unicorn.openServiceActivity(context, title, source);
    }

    public static void trackUserAccess(String url, String description) {
        if (!sCustomerServiceEnable) {
            return;
        }
        Unicorn.trackUserAccess(url, description);
    }

    public static int getUnreadCount() {
        if (!sCustomerServiceEnable) {
            return 0;
        }
        return Unicorn.getUnreadCount();
    }

    public static void addUnreadCountChangeListener(UnreadCountChangeListener listener, boolean add) {
        if (!sCustomerServiceEnable) {
            return;
        }
        Unicorn.addUnreadCountChangeListener(listener, add);
    }

    public static void setUserInfo(YSFUserInfo ysfUserInfo) {
        if (!sCustomerServiceEnable) {
            return;
        }
        Unicorn.setUserInfo(ysfUserInfo);
    }

    public static void setDevServer(int devServer) {
        if (!sCustomerServiceEnable) {
            return;
        }
        Unicorn.setDevServer(devServer);
    }

    private static YSFOptions ysfOptions() {
        YSFOptions options = new YSFOptions();
        options.statusBarNotificationConfig = new StatusBarNotificationConfig();
        options.savePowerConfig = new SavePowerConfig();
        options.uiCustomization = new UICustomization();
        return options;
    }

    private static boolean isUserChanged(String userId) {
        String prevUserId = CustomerServiceHelper.getLoggedInUserId();
        if (userId == null) {
            userId = "";
        }
        if (prevUserId == null) {
            prevUserId = "";
        }

        NfsLog.d(TAG, "prevUserId:" + prevUserId);
        NfsLog.d(TAG, "currUserId:" + userId);
        return !userId.equals(prevUserId);
    }

    private static String getLoggedInUserId() {
        return CustomerServicePreferencesHelper.getUserId();
    }

}
